package com.ruoyi.device.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.device.domain.DeviceInfo;
import com.ruoyi.device.mapper.DeviceInfoMapper;
import com.ruoyi.device.service.IDeviceSyncService;

/**
 * 设备同步服务实现类
 * 
 * @author ruoyi
 * @date 2025-10-29
 */
@Service
public class DeviceSyncServiceImpl implements IDeviceSyncService 
{
    private static final Logger log = LoggerFactory.getLogger(DeviceSyncServiceImpl.class);
    
    /**
     * 第三方接口地址
     */
    private static final String THIRD_PARTY_API_URL = "https://5g.report.szafx.cn/5g/m_info";
    
    /**
     * UUID固定值（根据实际情况可以配置）
     */
    private static final String UUID = "9860c4af-b020-4d62-aabc-29eb42c15639";
    
    @Autowired
    private DeviceInfoMapper deviceInfoMapper;
    
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 同步所有设备信息
     */
    @Override
    public void syncAllDevices() 
    {
        try {
            log.info("开始同步所有设备信息...");
            
            // 查询所有设备
            DeviceInfo queryParam = new DeviceInfo();
            List<DeviceInfo> deviceList = deviceInfoMapper.selectDeviceInfoList(queryParam);
            
            int successCount = 0;
            int failCount = 0;
            
            for (DeviceInfo device : deviceList) {
                try {
                    syncDeviceInfo(device.getDeviceId());
                    successCount++;
                } catch (Exception e) {
                    failCount++;
                    log.error("同步设备[{}]失败: {}", device.getDeviceId(), e.getMessage());
                }
            }
            
            log.info("设备信息同步完成，成功: {}, 失败: {}", successCount, failCount);
        } catch (Exception e) {
            log.error("同步所有设备信息失败: ", e);
        }
    }

    /**
     * 同步单个设备信息
     */
    @Override
    public void syncDeviceInfo(String deviceId) 
    {
        try {
            // 调用第三方接口
            JSONObject responseData = callThirdPartyApi(deviceId);
            
            if (responseData == null) {
                log.warn("设备[{}]未获取到有效数据", deviceId);
                return;
            }
            
            // 解析响应数据
            JSONObject equipment = responseData.getJSONObject("equipment");
            if (equipment == null) {
                log.warn("设备[{}]响应数据中没有equipment信息", deviceId);
                return;
            }
            
            // 计算在线人数
            int connectedNum = equipment.getIntValue("connected_num", 0);
            int connectedNum5g = equipment.getIntValue("connected_num_5g", 0);
            int totalConnections = connectedNum + connectedNum5g;
            
            // 获取连接客户端信息
            String connectedClients = buildConnectedClientsJson(equipment);
            
            // 判断设备是否在线
            Boolean online = equipment.getBoolean("online");
            int status = (online != null && online) ? 1 : 0; // 1-在线, 0-离线
            
            // 更新设备信息
            DeviceInfo updateDevice = new DeviceInfo();
            updateDevice.setDeviceId(deviceId);
            updateDevice.setCurrentConnections(totalConnections);
            updateDevice.setConnectedClients(connectedClients);
            updateDevice.setStatus(status);
            
            deviceInfoMapper.updateDeviceInfo(updateDevice);
            
            log.debug("设备[{}]同步成功，在线人数: {}, 状态: {}", deviceId, totalConnections, status == 1 ? "在线" : "离线");
            
        } catch (Exception e) {
            log.error("同步设备[{}]信息失败: ", deviceId, e);
            throw new RuntimeException("同步设备信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 调用第三方接口
     */
    private JSONObject callThirdPartyApi(String deviceId) 
    {
        try {
            // 构建请求参数
            Map<String, String> requestBody = new HashMap<>();
            requestBody.put("uuid", UUID);
            requestBody.put("recharge_number", deviceId);
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            // 发送POST请求
            HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);
            ResponseEntity<String> response = restTemplate.exchange(
                THIRD_PARTY_API_URL,
                HttpMethod.POST,
                request,
                String.class
            );
            
            // 解析响应
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                JSONObject jsonResponse = JSON.parseObject(response.getBody());
                
                // 检查success字段
                Boolean success = jsonResponse.getBoolean("success");
                if (success != null && success) {
                    return jsonResponse.getJSONObject("data");
                } else {
                    log.warn("第三方接口返回失败，DeviceId: {}, message: {}", deviceId, jsonResponse.getString("message"));
                }
            }
            
            return null;
        } catch (Exception e) {
            log.error("调用第三方接口失败，DeviceId: {}, 错误: ", deviceId, e);
            return null;
        }
    }
    
    /**
     * 构建连接客户端JSON字符串
     */
    private String buildConnectedClientsJson(JSONObject equipment) 
    {
        try {
            // 获取2.4G和5G的连接客户端
            Object clients2g = equipment.get("connected_clients");
            Object clients5g = equipment.get("connected_clients_5g");
            
            // 合并两个数组
            List<Object> allClients = new java.util.ArrayList<>();
            if (clients2g != null && clients2g instanceof List) {
                allClients.addAll((List<?>) clients2g);
            }
            if (clients5g != null && clients5g instanceof List) {
                allClients.addAll((List<?>) clients5g);
            }
            
            // 转换为JSON字符串
            return JSON.toJSONString(allClients);
        } catch (Exception e) {
            log.error("构建连接客户端JSON失败: ", e);
            return "[]";
        }
    }
}

